<?php
require_once(dirname(__FILE__).'/../config/db_connect.php');

class Information {

    private $error = array();
    private $title;
    private $txt;
    private $id;

    public function setValues($data) {
       $this->id =  empty($data['id']) ? '' : strip_tags(trim($data['id']));
       $this->title = empty($data['title']) ? '' : strip_tags(trim($data['title']));
       $this->txt =  empty($data['txt']) ? '' : strip_tags(trim($data['txt'])); 
        
    }
    public function reset() {
       $this->id = ''; 
       $this->title ='';
       $this->txt = ''; 
        
    }

    public function save($data) {

        $this->setValues($data); 
        if($this->getId()){
        		if($this->validate()){
        			 $update="UPDATE information SET title='$this->title', txt='$this->txt' WHERE id='$this->id' ";
                     mysql_query ($update);
                 }
        }			
        else {
        	if ($this->validate()) {
            mysql_query ("INSERT INTO information  VALUES ('','".$this->title."','".mysql_real_escape_string($this->txt)."','".date("Y-m-d")."')");
            $this->reset();
            //return $this->getinformation(mysql_insert_id());
          }
        }
    }

    public function loadInformationByID($id) {
        $select = "SELECT * FROM information WHERE id = '$id'";
        $resource = mysql_query($select);
        $this->setValues(mysql_fetch_assoc($resource));

    }

    public function getAllInformations() {
        
        $select = "SELECT * FROM information ORDER BY created_at DESC";
        $resource = mysql_query($select);
		    $informations = array();
        while($information = mysql_fetch_object($resource)) {
        	  $informations[] = $information;
        } 
        return $informations; 
    }    

    private function validate() {

        if (empty($this->title)) {
             $this->addError("title","Saisissez le titre");
        }
        if (empty($this->txt)) {
             $this->addError("txt","Saisissez le texte");
        }
          if(count($this->error) > 0) {
            return false;
        } else {
            return true;
        }      
    }

   private function addError($index, $error) {
        $this->error[$index] =  $error;
    }

    public function getError($index) { 
      if(!empty($this->error[$index])) {
        return '<div class="alert alert-error">'.$this->error[$index].'</div>';
      }
    }
    public function hasError() {
       return count($this->error) > 0 ? true : false;
    }

    public function getTitle(){
    	return $this->title;
    }
    public function getId(){
        return $this->id;
    }    
    public function getTxt(){
    	return $this->txt;
    }
}
